const { Op } = require('sequelize');
const models = require('../models');
const DateUtils = require('../utils/dateUtils');
const { sys_user_model: SysUserModel, sys_user_role_model: SysUserRoleModel,sys_role_model: SysRoleModel, sys_menu_model: SysMenuModel, sys_role_menu_model: SysRoleMenuModel  } = models;
const { realDelete } = require('../config/system');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { JWT_SECRET } = require('../config/system');

class UserService {
  // 获取用户列表
  async getUserList({ page, size, username, deptId, status }) {
    const where = {};
    if (username) {
      where.username = { [Op.like]: `%${username}%` };
    }
    if (status !== undefined) {
      where.status = status;
    }
    if (deptId) {
      where.dept_id = deptId;
    }
    where.is_deleted = 0; // 未删除

    const { count, rows } = await SysUserModel.findAndCountAll({
      where,
      offset: (page - 1) * size,
      limit: size,
      order: [['create_time', 'DESC']],
      attributes: { exclude: ['password'] }, // 排除密码字段
      include: [{
        model: models.sys_dept_model,
        as: 'dept',
        attributes: ['name'],
        required: false,
        foreignKey: 'dept_id',
        targetKey: 'id'
      }]
    });

    // 处理返回结果，将部门信息添加到用户数据中
    const formattedRows = rows.map(row => {
      const plainRow = row.get({ plain: true });
      return {
        ...plainRow,
        deptName: plainRow.dept ? plainRow.dept.name : null,
      };
    });

    return {
      count: count,
      rows: formattedRows
    };
  }

  // 获取用户详情
  async getUserById(id) {
    const user = await SysUserModel.findOne({
      where: { id, is_deleted: 0 },
      attributes: { exclude: ['password'] }
    });
    if (!user) {
      throw new Error('用户不存在');
    }
    return user;
  }

  // 创建用户
  async createUser(userData) {
    // 检查用户名是否已存在
    const existUser = await SysUserModel.findOne({
      where: { username: userData.username, is_deleted: 0 }
    });
    if (existUser) {
      throw new Error('用户名已存在');
    }

    // 密码加密处理
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(userData.password, salt);

    const result = await SysUserModel.create({
      ...userData,
      password: hashedPassword,
      createTime: DateUtils.getCurrentTime(),
      isDeleted: 0
    });

    return result;
  }

  // 更新用户
  async updateUser(id, userData) {
    const user = await SysUserModel.findOne({
      where: { id, is_deleted: 0 }
    });
    if (!user) {
      throw new Error('用户不存在');
    }

    // 如果修改用户名，需要检查是否重复
    if (userData.username && userData.username !== user.username) {
      const existUser = await SysUserModel.findOne({
        where: { username: userData.username, is_deleted: 0, id: { [Op.ne]: id } }
      });
      if (existUser) {
        throw new Error('用户名已存在');
      }
    }

    // 如果更新密码，需要加密
    if (userData.password) {
      const salt = await bcrypt.genSalt(10);
      userData.password = await bcrypt.hash(userData.password, salt);
    }

    await user.update({
      ...userData,
      update_time: DateUtils.getCurrentTime(),
      update_by: userData.update_by
    });

    return user;
  }

  // 删除用户
  async deleteUser(id) {
    const user = await SysUserModel.findOne({
      where: { id, isDeleted: 0 }
    });
    if (!user) {
      throw new Error('用户不存在');
    }

    // 使用事务确保数据一致性
    const t = await models.sequelize.transaction();
    try {
      if (realDelete) {
        // 真实删除用户角色关联
        await SysUserRoleModel.destroy({
          where: { userId: id },
          transaction: t
        });
        // 真实删除用户
        await user.destroy({ transaction: t });
      } else {
        // 软删除
        await user.update({
          is_deleted: 1,
          update_time: DateUtils.getCurrentTime()
        }, { transaction: t });
      }
      await t.commit();
    } catch (error) {
      await t.rollback();
      throw error;
    }
  }

  // 分配用户角色
  async assignUserRoles(userId, roleIds) {
    const user = await SysUserModel.findOne({
      where: { id: userId, isDeleted: 0 }
    });
    if (!user) {
      throw new Error('用户不存在');
    }

    // 使用事务确保数据一致性
    const t = await models.sequelize.transaction();
    try {
      // 删除原有角色关联
      await SysUserRoleModel.destroy({
        where: { userId: userId },
        transaction: t
      });

      // 创建新的角色关联
      if (roleIds && roleIds.length > 0) {
        const userRoles = roleIds.map(roleId => ({
          user_id: userId,
          role_id: roleId
        }));
        await SysUserRoleModel.bulkCreate(userRoles, { transaction: t });
      }

      await t.commit();
    } catch (error) {
      await t.rollback();
      throw error;
    }
  }

  // 获取用户角色
  async getUserRoles(userId) {
    const roles = await SysRoleModel.findAll({
      include: [{
        model: SysUserRoleModel,
        where: { user_id: userId },
        attributes: []
      }]
    });
    return roles;
  }

  // 获取当前用户信息
  async getCurrentUserInfo(userId) {
    // 获取用户基本信息
    const user = await SysUserModel.findOne({
      where: { id: userId, is_deleted: 0 },
      attributes: ['id', 'username', 'nickname', 'avatar']
    });

    if (!user) {
      throw new Error('用户不存在');
    }

    // 获取用户角色
    const roles = await this.getUserRoles(userId);
    const roleNames = roles.map(role => role.code);
    const roleIds = roles.map(role => role.id);

    // 获取角色关联的菜单权限
    const menus = await SysMenuModel.findAll({
      include: [{
        model: SysRoleMenuModel,
        where: { role_id: { [Op.in]: roleIds } },
        attributes: []
      }],
      where: {
        perm: { [Op.ne]: null , [Op.ne]: ''  },
        type: 4  // 只查询按钮类型的菜单
      },
      attributes: ['perm']
    });

    // 提取权限标识并去重
    const perms = [...new Set(menus.map(menu => menu.perm).filter(Boolean))];

    return {
      userId: user.id,
      username: user.username,
      nickname: user.nickname || '',
      avatar: user.avatar || '',
      roles: roleNames,
      perms: perms
    };
  }

  // 用户登录
  async login(username, password) {
    // 查找用户
    const user = await SysUserModel.findOne({
      where: { username, is_deleted: 0 }
    });

    if (!user) {
      throw new Error('用户不存在');
    }

    // 验证密码
    const isMatch = await bcrypt.compare(password, user.password);
    if (!isMatch) {
      throw new Error('密码错误');
    }

    // 检查用户状态
    if (user.status === 0) {
      throw new Error('用户已被禁用');
    }

    // 生成JWT token
    const token = jwt.sign(
      { 
        id: user.id,
        username: user.username
      },
      JWT_SECRET,
      { expiresIn: '24h' }
    );

    // 更新登录时间
    await user.update({
      last_login_time: DateUtils.getCurrentTime()
    });

    return {
      token,
      user: {
        id: user.id,
        username: user.username,
        nickname: user.nickname,
        avatar: user.avatar,
        email: user.email,
        status: user.status
      }
    };
  }

  // 获取用户表单详情
  async getUserForm(id) {
    // 获取用户基本信息
    const user = await SysUserModel.findOne({
      where: { id, is_deleted: 0 },
      attributes: { exclude: ['password'] },
      raw: true
    });

    if (!user) {
      throw new Error('用户不存在');
    }

    // 获取用户角色ID列表
    const userRoles = await SysUserRoleModel.findAll({
      where: { user_id: id },
      attributes: ['role_id'],
      raw: true
    });

    // 构造返回数据
    const userForm = {
      id: user.id,
      username: user.username,
      nickname: user.nickname,
      mobile: user.mobile,
      gender: user.gender,
      avatar: user.avatar,
      email: user.email,
      status: user.status,
      deptId: user.dept_id,
      roleIds: userRoles.map(role => role.role_id),
      openId: user.open_id
    };

    return userForm;
  }

  // 修改用户密码
  async updatePassword(id, newPassword) {
    // 查找用户
    const user = await SysUserModel.findOne({
      where: { id, isDeleted: 0 }
    });

    if (!user) {
      throw new Error('用户不存在');
    }

    // 加密新密码
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(newPassword, salt);

    // 更新密码
    await user.update({
      password: hashedPassword,      update_time: DateUtils.getCurrentTime()
    });
  }

  async changePassword(id, oldPassword, newPassword) {
    // 查找用户
    const user = await SysUserModel.findOne({
      where: { id, isDeleted: 0 }
    });

    if (!user) {
      throw new Error('用户不存在');
    }

    // 验证旧密码
    const isMatch = await bcrypt.compare(oldPassword, user.password);
    if (!isMatch) {
      throw new Error('旧密码错误');
    }

    // 加密新密码
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(newPassword, salt);

    // 更新密码
    await user.update({
      password: hashedPassword,
      update_time: DateUtils.getCurrentTime()
    });
  }
}

module.exports = new UserService();
